package com.woorigil.social.parser.tmon;

import java.io.IOException;
import java.io.Reader;
import java.util.Map;

import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.woorigil.social.DateUtils;
import com.woorigil.social.domain.ProviderCode;
import com.woorigil.social.domain.deal.Deal;
import com.woorigil.social.domain.deal.DealListDocument;
import com.woorigil.social.domain.deal.ManageStatus;
import com.woorigil.social.parser.EtcCategoryUtils;
import com.woorigil.social.parser.LocalCategoryUtils;
import com.woorigil.social.parser.XmlParser;

@Component (value="tmonXmlParser")
public class TmonXmlParser extends XmlParser {
	private static Logger log = LoggerFactory.getLogger(TmonXmlParser.class);
	
	@Autowired TmonHtmlParser tmonHtmlParser;
	
	@Value("${tmon.deal.path}") 
	String dealPath;

	@Override
	public String getCharsetName() {
		return "UTF-8";
	}

	@Override
	public ProviderCode getProviderCode() {
		return ProviderCode.TM;
	}
	
	@Override
	public String getSourcePath() {
		return dealPath;
	}

	@Override
	public DealListDocument parse(Reader reader) throws ValidityException, ParsingException, IOException {
		Map<String, TmonExtraDeal> tmonExtraDeals = tmonHtmlParser.parse();
		
		Builder builder = new Builder();
		Document doc = builder.build(reader);
		Element root = doc.getRootElement();

		DealListDocument dealListDocument = new DealListDocument();
		dealListDocument.setSourceProvider("티몬");
		dealListDocument.setVersion("0.0");
		
		Elements dealsEles = root.getChildElements();
		for (int i = 0; i < dealsEles.size(); i++) {
			if (i == 0) {
				continue;
			}
			Element dealEl = dealsEles.get(i);
			
			Deal deal = new Deal();
			deal.setProviderCode(getProviderCode());
			deal.setMetaId(getValue(dealEl.getFirstChildElement("pid")));
			deal.setCategory(getValue(dealEl.getFirstChildElement("division")));
			deal.setSaleStartAt(DateUtils.toDate(getValue(dealEl.getFirstChildElement("startdate")), "yyyy-MM-dd HH:mm:ss"));//2012-11-29 00:00:00
			deal.setSaleEndAt(DateUtils.toDate(getValue(dealEl.getFirstChildElement("limitdate")), "yyyy-MM-dd HH:mm:ss"));
			deal.setTitle(getValue(dealEl.getFirstChildElement("name")));
			deal.setWebLink(getValue(dealEl.getFirstChildElement("url")));
			deal.setOriginalPrice(NumberUtils.toInt(getValue(dealEl.getFirstChildElement("price")), 0));
			deal.setSalesPrice(NumberUtils.toInt(getValue(dealEl.getFirstChildElement("saleprice")), 0));
			deal.setDiscountRate(NumberUtils.toInt(getValue(dealEl.getFirstChildElement("salerate")), 0));
			deal.setMaxCount(NumberUtils.toInt(getValue(dealEl.getFirstChildElement("maxcnt")), 0));
			deal.setMinCount(NumberUtils.toInt(getValue(dealEl.getFirstChildElement("mincnt")), 0));
			deal.setNowCount(NumberUtils.toInt(getValue(dealEl.getFirstChildElement("salecnt")), 0));
//			deal.setSalesStatus(getValue(dealEl.getFirstChildElement("type")));
			deal.setImageUrl1(getValue(dealEl.getFirstChildElement("image1")));
			deal.setImageUrl2(getImageUrl2(deal.getImageUrl1(), getValue(dealEl.getFirstChildElement("image2"))));
		
			if (isNotShoppingDeal(tmonExtraDeals.get(deal.getMetaId()))) {
				deal.setShopAddress(getValue(dealEl.getFirstChildElement("address")));	
				deal.setShopLatitude(isValidLocation(getValue(dealEl.getFirstChildElement("lat"))));
				deal.setShopLongitude(isValidLocation(getValue(dealEl.getFirstChildElement("lng"))));
			}
				
			deal.setImageUrl(deal.getImageUrl2());
			deal.setAverageCount((int)(deal.getNowCount() / DateUtils.getTodayCount(deal.getSaleStartAt())));
			deal.setManageStatus(ManageStatus.S);
			deal.setCategoryId(findCategoryId(deal, tmonExtraDeals.get(deal.getMetaId())));
			dealListDocument.add(deal);
		}
		
		log.info(getProviderCode() + " deal size : " + dealListDocument.getDeals().size());
		
		return dealListDocument;
	}
	
	private String getImageUrl2(String imageUrl1, String imageUrl2) {
		if (StringUtils.isEmpty(imageUrl2)) {
			return imageUrl1;
		}
		return imageUrl2;
	}

	private String isValidLocation(String value) {
		if (StringUtils.isBlank(value)) {
			return null;
		}
		
		if (value.length() < 2) {
			return null;
		}
		return value;
	}

	private boolean isNotShoppingDeal(TmonExtraDeal tmonExtraDeal) {
		if (tmonExtraDeal == null) {
			return true;
		}
		return false;
	}

	private int findCategoryId(Deal deal, TmonExtraDeal tmonExtraDeal) {
		if (tmonExtraDeal != null) {
			return tmonExtraDeal.getCategoryId();
		}
		
		if ("지역>뷰티>".equals(deal.getCategory())) {
			return LocalCategoryUtils.getButiCategoryId(deal.getShopAddress());
		} else if ("지역>생활>".equals(deal.getCategory())) {
			return LocalCategoryUtils.getButiCategoryId(deal.getShopAddress());
		} else if ("지역>맛집>".equals(deal.getCategory())) {
			return LocalCategoryUtils.getFoodCategoryId(deal.getShopAddress());
		} else {
			return EtcCategoryUtils.getCategoryId(deal.getCategory());
		}
	}
}
